<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>

    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            不合格条码重置
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:60px;">

        <div id="citemList" class="aui-content">

            <ul class="aui-list aui-form-list">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">产品条码</div>
                        <div class="aui-list-item-input">
                            <input id="barcode"></input>
                        </div>
                    </div>
                </li>


            </ul>

        </div>

        <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;">
            <table class="table" style='width:100%;' id="table">
                <thead>
                    <tr
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 12px;font-weight: bold;">
                        <td algin='center'>序号</td>
                        <td algin='center'>产品条码</td>
                        <td algin='center'>工序</td>
                        <td algin='center'>工位</td>
                        <td algin='center'>状态</td>
                    </tr>
                </thead>
                <tbody id="tbodyHtml">
                </tbody>
            </table>
        </div>

    </div>
    <div id="addpicss" class="aui-content" style="background-color: #ffffff">
        <ul class="aui-list-view aui-grid-view" id="imgslist">
            <li class="aui-list-view-cell aui-img aui-col-xs-4" id="addpic" onclick="imgClick()">
                <img class="aui-img-object" src="../image/add.jpg">
            </li>
        </ul>
    </div>
    <div class='aui-btn aui-btn-info' style='width:40%;margin-top: 30%;margin-left:7%' onclick='doSaveHg()'>合格</div>
    <div class='aui-btn aui-btn-info' style='width:40%;margin-top: 30%;margin-left:6%' onclick='doSaveBhg()'>不合格</div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript">

    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;

    var sysid = '';
    //初始化
    apiready = function () {

        $("#barcode").focus();
        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');
    };


    function doSaveHg() {
        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names));
        if (picNames == '' || picNames == null) {
            api.toast({
                msg: "请先拍照上传图片后再重置条码！",
                duration: 3000
            });
            return
        }
        api.confirm({
            title: '提示',
            msg: "是否将该条码状态改为合格？",
            buttons: ['确定', '取消']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            if (index == 1) {
                api.showProgress({
                    title: '保存中...',
                });
                var un = localStorage.getItem('un');
                var serverUrl = localStorage.getItem('serverUrl');
                var url = serverUrl + "/app/saveProductNew";
                var params = new Object();
                params.url = url;
                params.dataType = 'json';
                params.method = 'post';
                var data = {
                    values: { ////以表单方式提交参数（JSON对象）
                        sysid: sysid,
                        flag: '合格',
                        picNames: picNames,
                        un: un
                    }
                };
                api.ajax({
                    url: url,
                    method: 'post',
                    dataType: 'json',
                    timeout: 30,
                    returnAll: false,
                    data: data
                }, function (ret, err) {
                    if (ret) {

                        var data = JSON.stringify(ret);
                        var myobj = eval("(" + data + ")");
                        //成功
                        if (myobj.code == '0') {
                            clearContent();
                            api.hideProgress();
                            doSearch()
                            api.toast({
                                msg: "保存成功",
                                duration: 3000
                            });
                        } else {
                            api.hideProgress();
                            api.toast({
                                msg: myobj.msg,
                                duration: 3000
                            });
                        }
                    }
                });
            }
        }
        )


    }
    function clearContent() {

        var div = document.getElementById('addpicss');
        div.innerHTML = '';
        var html = "";
        html += "<div style='width: 100%;margin-top:1%;border:solid 1px #D3D3D3;overflow: hidden;'>";
        html += "<div class='aui-content' style='background-color: #ffffff'>";
        html += "<ul class='aui-list-view aui-grid-view' id='imgslist'>";
        html += "<li class='aui-list-view-cell aui-img aui-col-xs-4' id='addpic' ' onclick='imgClick()'>";
        html += "<img class='aui-img-object' src='../image/add.jpg'>";
        html += "</li> </ul></div></div>";

        $api.html($api.byId("addpicss"), html);

    }
    //保存成功后，清除图片
    function removeImg() {
        var imgs = document.getElementsByTagName('img');
        console.log(imgs.length + "0000")
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            console.log(img + "1111" + i)
            var srcStr = img.getAttribute('src');
            var obj = $("#imgslist img[src='" + srcStr + "']").parent("li");
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            console.log(nameStr + "222" + i)
            if ("add.jpg" != nameStr) {
                console.log(nameStr + "333" + i)
                $(obj).remove();
            }
        }
    }

    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();
        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            if (ret.list) {
                                for (var i = 0; i < ret.list.length; i++) {
                                    var selectImg = ret.list[i];
                                    // 获取图片的路径
                                    var selectimgPath = selectImg.path;
                                    var selectimgThumbPath = selectImg.thumbPath;
                                    // 图片压缩
                                    imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                        var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                            "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                        // 追加图片
                                        $("#addpic").before(showImgHtml);
                                        // ########################################  绑定长按事件 ########################
                                        addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                        // ################### 上传图片 #########################
                                        uploadFile(compressImg);
                                    });
                                }
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 为图片添加点击预览功能,排除添加按钮
    function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }


    function doSaveBhg() {
        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names));
        if (picNames == '' || picNames == null) {
            api.toast({
                msg: "请先拍照上传图片后再重置条码！",
                duration: 3000
            });
            return
        }
        api.confirm({
            title: '提示',
            msg: "是否将该条码状态改为不合格？",
            buttons: ['确定', '取消']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            if (index == 1) {
                api.showProgress({
                    title: '保存中...',
                });
                var un = localStorage.getItem('un');
                var serverUrl = localStorage.getItem('serverUrl');
                var url = serverUrl + "/app/saveProductNew";
                var params = new Object();
                params.url = url;
                params.dataType = 'json';
                params.method = 'post';
                var data = {
                    values: { ////以表单方式提交参数（JSON对象）
                        sysid: sysid,
                        flag: '不合格',
                        picNames: picNames,
                        un: un
                    }
                };
                api.ajax({
                    url: url,
                    method: 'post',
                    dataType: 'json',
                    timeout: 30,
                    returnAll: false,
                    data: data
                }, function (ret, err) {
                    if (ret) {

                        var data = JSON.stringify(ret);
                        var myobj = eval("(" + data + ")");
                        //成功
                        if (myobj.code == '0') {
                            clearContent();
                            api.hideProgress();
                            doSearch()

                            api.toast({
                                msg: "保存成功",
                                duration: 3000
                            });
                        } else {
                            api.hideProgress();
                            api.toast({
                                msg: myobj.msg,
                                duration: 3000
                            });
                        }
                    }
                });
            }
        }
        )


    }


    //产品条码监听回车事件
    $("#barcode").on('keypress', function (e) {
        var keycode = e.keyCode;
        var tm = $(this).val();
        if (keycode == '13') {
            doSearch()
        }
    });

    //查询
    function doSearch() {
        api.showProgress({
            title: '查询中...',
        });
        var produBarcode = $("#barcode").val();
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/selectProduct";
        var data = {
            values: {
                produBarcode: produBarcode,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                api.hideProgress();
                //返回成功
                if (myobj.code == "0") {
                    var list = eval(myobj.list);
                    var html = "";
                    for (var i = 0; i < list.length; i++) {
                        html += "<tr style='text-align: center;color: black;font-size: 10px;background-color: #F5F5F5;'>";
                        html += "<td name='seqno'>" + (i + 1) + "</td>";
                        html += "<td name='produBarcode'>" + list[i].produBarcode + "</td>";
                        html += "<td name='opCode'>" + list[i].opCode + "</td>";
                        html += "<td name='workCellCode'>" + list[i].workCellCode + "</td>";
                        html += "<td name='checkFlag'>" + list[i].checkFlag + "</td>";
                        html += "</tr>";
                        sysid = list[i].sysid
                    }
                    $api.html($api.byId("tbodyHtml"), html);

                    //失败
                } else if (myobj.code == "1") {
                    api.hideProgress();
                    $("#barcode").val("")
                    sysid = '';

                    //清空表格数据
                    $api.html($api.byId("tbodyHtml"), "");
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.hideProgress();
            }
        });
    }





    //返回按钮
    function closeWin() {
        // 
        if (api.pageParam.barcode == undefined) {
            api.closeWin({});
        } else {
            api.closeToWin({ name: api.pageParam.name });
            api.execScript({
                name: api.pageParam.name,
                script: 'refreshData()'
            });
        }
    }


</script>

</html>